import router from '@/router'
import store from '@/store'
router.beforeEach((to, from, next) => {
  if (store.state.user.token) {
    // 登录
    if (to.path === '/login') {
      next('/')
    } else {
      // 判断是否有用户id
      if (!store.getters.userId) {
        store.dispatch('user/userInfoAction')
      }
      next()
    }
  } else {
    // 未登录
    // 设置白名单。(不需要登录就能访问的页面)
    const writhList = ['/login', '/404']
    if (writhList.includes(to.path)) {
      next()
    } else {
      // console.log('没有权限哦')
      next('/login')
    }
  }
})

router.afterEach((to) => {
  const whiteList = ['/login']
  if (whiteList.includes(to.path)) {
    return
  }
  const historyInfo = store.state.user.historyInfo
  const index = historyInfo.findIndex((item) => item.name === to.path)
  if (index === -1) {
    const obj = { name: to.path, title: to.meta.title }
    store.commit('user/changeHistoryInfo', obj)
  }
})
